package com.lier.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.lier.common.constant.ProductConstant;
import com.lier.common.to.SkuReductionTo;
import com.lier.common.to.SpuBoundsTo;
import com.lier.common.to.es.SkuEsModel;
import com.lier.common.utils.R;
import com.lier.common.vo.SkuHasStockVo;
import com.lier.gulimall.product.dao.AttrDao;
import com.lier.gulimall.product.entity.*;
import com.lier.gulimall.product.feign.CouponFeignService;
import com.lier.gulimall.product.feign.SearchFeignService;
import com.lier.gulimall.product.feign.WareFeignService;
import com.lier.gulimall.product.service.*;
import com.lier.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lier.common.utils.PageUtils;
import com.lier.common.utils.Query;
import com.lier.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;


/**
 *
 * @author 66447
 */
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    private SpuInfoDescService spuInfoDescService;
    @Resource
    private SpuImagesService spuImagesService;
    @Resource
    private AttrDao attrDao;
    @Resource
    private ProductAttrValueService productAttrValueService;
    @Resource
    private SkuInfoService skuInfoService;
    @Resource
    private SkuImagesService skuImagesService;
    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    private CouponFeignService couponFeignService;
    @Resource
    private BrandService brandService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private AttrService attrService;
    @Resource
    private WareFeignService wareFeignService;
    @Resource
    private SearchFeignService searchFeignService;
    @Autowired
    private SpuInfoService spuInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {

        // 保存spu基本信息: pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        baseMapper.insert(spuInfoEntity);

        // 保存spu描述图片: pms_spu_info_desc
        List<String> decriptList = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decriptList));
        spuInfoDescService.saveSpuInfo(spuInfoDescEntity);

        // 保存spu的图片集: pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        // 保存spu的基础属性(规格参数): pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrDao.selectById(attr.getAttrId());
            if(attrEntity != null){
                productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            }
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntityList);

        // 保存spu对应的积分信息(跨数据库): gulimall-sms: sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if(r.getCode() != 0){
            log.error("远程保存spu优惠和积分信息失败");
        }


        List<Skus> skus = spuSaveVo.getSkus();
        if(skus != null && !skus.isEmpty()){
            skus.forEach(sku -> {

                // 获取sku的默认图片
                String defaultImg = "";
                for(Images image : sku.getImages()){
                    if(image.getDefaultImg() == 1){
                        defaultImg = image.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);

                // 保存对应sku的基本信息: pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity);

                // 保存sku的图片信息: pms_sku_images
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> skuImagesEntities = sku.getImages().stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);

                // 保存sku的销售属性: pms_sku_sale_attr_value
                List<Attr> attrList = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrList.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);

                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());

                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // 保存的sku的优惠满减等信息(跨数据库): gulimall-sms: sms_sku_ladder/sms_sku_full_reduction/sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0)) > 0){
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if(r1.getCode() != 0){
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }
    }

    @Override
    public PageUtils queryPagByCondition(Map<String, Object> params) {

        LambdaUpdateWrapper<SpuInfoEntity> queryWrapper = new LambdaUpdateWrapper<>();

        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)){

            queryWrapper.and(wrapper -> {
                wrapper.eq(SpuInfoEntity::getId, key).or().like(SpuInfoEntity::getSpuName, key);
            });
        }


        String status = (String)params.get("status");
        if(!StringUtils.isEmpty(status)){
            queryWrapper.eq(SpuInfoEntity::getPublishStatus, status);
        }

        String brandId = (String)params.get("brandId");
        if(!"0".equals(brandId) && !StringUtils.isEmpty(brandId)){
            queryWrapper.eq(SpuInfoEntity::getBrandId, brandId);
        }

        String catelogId = (String)params.get("catelogId");
        if(!"0".equals(catelogId) && !StringUtils.isEmpty(catelogId)){
            queryWrapper.eq(SpuInfoEntity::getCatalogId, catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void spuUp(Long spuId) {

        SpuInfoEntity spuInfoEntity = spuInfoService.getById(spuId);
        if(spuInfoEntity == null || spuInfoEntity.getPublishStatus() != ProductConstant.StatusEnum.NEW_SPU.getCode()) {
            log.error("上架商品不存在, 或者改商品不处于新建状态");
            return;
        }

        // 组转数据
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBuSpuId(spuId);

        // 获取当前sku的所有可以用来检索规格属性
        List<ProductAttrValueEntity> productAttrValueEntityList = productAttrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIdList = productAttrValueEntityList.stream().map(ProductAttrValueEntity::getAttrId)
                .collect(Collectors.toList());

        List<Long> attrs = attrService.selectSearchAttrs(attrIdList);
        Set<Long> attrIdSet = new HashSet<>(attrs);

        List<SkuEsModel.Attrs> attrsModelList = productAttrValueEntityList.stream()
                .filter(item -> attrIdSet.contains(item.getAttrId()))
                .map(item -> {
                    SkuEsModel.Attrs attrsModel = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(item, attrsModel);
                    return attrsModel;
        }).collect(Collectors.toList());

        // 远程库存系统是否有库存
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Boolean> stockMap = null;
        try{
            R r = wareFeignService.getSkusHasStock(skuIds);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            List<SkuHasStockVo> stockDataList = r.getData(typeReference);
            stockMap = stockDataList.stream()
                    .collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
        }catch (Exception e){
            log.error("库存查询异常: 原因{}", e);
        }


        // 构造检索数据
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> skuEsModelList = skuInfoEntities.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel);
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());

            // 设置是否有库存
            if(finalStockMap == null){
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }
            skuEsModel.setHotScore(0L);
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity category = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatelogId(sku.getCatalogId());
            skuEsModel.setCatelogName(category.getName());

            // 设置检索属性
            skuEsModel.setAttrs(attrsModelList);

            return skuEsModel;
        }).collect(Collectors.toList());

        // todo 远程检索服务将数据存入Elasticsearch中
        R r = searchFeignService.productStatusUp(skuEsModelList);
        if(r.getCode() == 0){
            //远程成功, 修改状态
            LambdaUpdateWrapper<SpuInfoEntity> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(SpuInfoEntity::getPublishStatus, ProductConstant.StatusEnum.SPU_UP.getCode())
                    .set(SpuInfoEntity::getUpdateTime, new Date())
                    .eq(SpuInfoEntity::getId, spuId);
            baseMapper.update(null, wrapper);
        }else {
            // todo 重复调用, 接口幂等性, 重试机制???



        }
    }

}
